<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;

/**
 * 经销商管理
 *
 * @icon fa fa-circle-o
 */
class Dealer extends Backend
{
    
    /**
     * Dealer模型对象
     * @var \app\admin\model\Dealer
     */
    protected $model = null;
    protected $searchFields = 'name';
    protected $noNeedLogin = ['detail','state'];

    // 数据限制
    protected $dataLimit = 'personal';
    protected $dataLimitField = 'id';
    protected $dataLimitFieldAutoFill = false;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dealer;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                // 经销商用户
                $dealer_consumer = Db::name('consumer')->where('dealer_id = '.$row['id'].' and is_dealer = "1"')->field('id')->find();

                // 店铺数
                $row['shop'] = Db::name('shop')->where('FIND_IN_SET(:id,dealer_ids)',['id' => $row['id']])->count();

                // 直播间数
                $row['studio'] = Db::name('studio')->where('FIND_IN_SET(:id,dealer_ids)',['id' => $row['id']])->count();

                // 用户数
                $row['users'] = Db::name('consumer')->where('dealer_id',$row['id'])->where('is_dealer',"0")->count();

                // 订单数
                $where_sql['dealer_id'] = $row['id'];
                $where_sql['status'] = ['<>','7'];
                $where_dis['dealer_id'] = $row['id'];

                if($dealer_consumer){
                    $where_sql['consumer_id'] = ['<>', $dealer_consumer['id']];
                    $where_dis['head_id'] = ['<>', $dealer_consumer['id']];
                }

                $row['orders'] = Db::name('order')->where($where_sql)->count();

                // 总分销数
                $row['distributions'] = Db::name('order')->where($where_dis)->sum('commission_available');

                // 总佣金数
                /*$commission = Db::name('consumer')
                    ->where('dealer_id = '.$row['id'].' and consumer_id = 0')
                    ->field('commission')->find()['commission'];*/
                $row['commissions'] = Db::name('order')->where('dealer_id',$row['id'])->sum('commission_available');
                $row->visible(['id','consumer','name','shop','studio','users','orders','commissions','distributions','status']);

            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = '')
    {
        $row = Db::name('dealer')
            ->where('id', $ids)
            ->field('id, name, phone, stime, etime, holder, account, bank')
            ->find();
        $row['shop'] = Db::name('shop')->where('FIND_IN_SET(:id,dealer_ids)',['id' => $ids])->count();
        $row['studio'] = Db::name('studio')->where('FIND_IN_SET(:id,dealer_ids)',['id' => $ids])->count();
        $row['users'] = Db::name('consumer')->where('dealer_id',$ids)->where('is_dealer','0')->count();

        // 经销商用户
        $dealer_consumer = Db::name('consumer')->where('dealer_id = '.$row['id'].' and is_dealer = "1"')->field('id')->find();

        // 订单数
        $where_sql['dealer_id'] = $row['id'];
        $where_sql['status'] = ['<>','7'];
        $where_dis['dealer_id'] = $row['id'];

        if($dealer_consumer){
            $where_sql['consumer_id'] = ['<>', $dealer_consumer['id']];
            $where_dis['head_id'] = ['<>', $dealer_consumer['id']];
        }

        $row['orders'] = Db::name('order')->where($where_sql)->count();

        // 总分销数
        $row['distributions'] = Db::name('order')->where($where_dis)->sum('commission_available');

        // 总佣金数
        $row['commissions'] = Db::name('order')->where('dealer_id',$row['id'])->sum('commission_available');

        $this->assign('data', $row);

        return $this->view->fetch();
    }

    /**
     * 状态切换
     */
    public function state($ids = '')
    {
        $row = $this->model->get($ids);
        if(!$row){
            $this->error(__("No results were found"));
        }

        if($this->request->isPost()){
            if($row->status == 0){
                $row->status = 1;
            }elseif($row->status == 1){
                $row->status = 0;
            }
            $row->save();
        }

        $rst = array(
            'code' => 1,
//            'msg' => '',
            'data' => $row,
            'url' => '.',
            'wait' => '3'
        );
        return json($rst);
    }
}
